package org.makcro.sms.services.chat.web.client.mvc.view;

import java.util.List;

import org.makcro.sms.services.chat.web.client.AppEvents;
import org.makcro.sms.services.chat.web.client.Constants;
import org.makcro.sms.services.chat.web.client.widgets.main.MessagesTabItem;
import org.makcro.sms.services.chat.web.client.widgets.main.AnsweredMessagesPanel;
import org.makcro.sms.services.chat.web.shared.dto.HistoryItemDto;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.data.BasePagingLoader;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.data.PagingLoader;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;

public class AgentsMessagesView extends View {

	private AnsweredMessagesPanel	panel;

	public AgentsMessagesView(Controller controller) {
		super( controller );

	}

	@Override
	protected void initialize() {
		super.initialize();
		panel = new AnsweredMessagesPanel();
		// setup loader
		RpcProxy<HistoryItemDto> agentMessagesRpcProxy = Registry.<RpcProxy<HistoryItemDto>>get( Constants.Services.AGENTS_MESSAGES_RPC_PROXY );
		PagingLoader<PagingLoadResult<HistoryItemDto>> pagingLoader = new BasePagingLoader<PagingLoadResult<HistoryItemDto>>( agentMessagesRpcProxy );
		panel.setPagingLoader( pagingLoader );
		// init panel
		panel.init();
		panel.setHeading( "Moje odgovorene poruke" );
	}

	@Override
	protected void handleEvent(AppEvent event) {
		EventType type = event.getType();

		if ( type == AppEvents.LoginSuccessful ) {
			onInit( event );
		}
		else if ( type == AppEvents.AGENT_MESSAGES_UPDATE ) {
			onUpdate(event);
		}

	}

	private void onUpdate(AppEvent event) {
		List<HistoryItemDto> dataUpdate = event.<List<HistoryItemDto>>getData();
		this.panel.getStore().removeAll();
		this.panel.getStore().add( dataUpdate );
	}

	private void onInit(AppEvent event) {
		BorderLayoutData layoutData = new BorderLayoutData( LayoutRegion.EAST );
		layoutData.setCollapsible( true );
//		layoutData.setMinSize( 500 );
		layoutData.setSize( 0.5f );
//		layoutData.setSplit( true );
		
		MessagesTabItem messagesTab = Registry.get( Constants.Ui.MESSAGES_TAB_ITEM );
		messagesTab.add( panel, layoutData );
		messagesTab.layout();

	}

}
